﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;

namespace Wwtfly.Utility
{
    /// <summary>
    ///  密码帮助
    /// </summary>
    public class PasswordHelper
    {

        /// <summary>
        /// ToString("X2") 为C#中的字符串格式控制符
        ///X为     十六进制 
        ///2为     每次都是两位数
        ///比如   0x0A ，若没有2,就只会输出0xA 
        /// </summary>
        /// <param name="buffer"></param>
        /// <returns></returns>
        public static string BytesToHex(byte[] buffer)
        {
            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < buffer.Length; i++)
            {
                builder.Append(buffer[i].ToString("X2"));
            }
            return builder.ToString();
        }

        /// <summary>
        /// MD5 加密码
        /// </summary>
        /// <param name="input">输入字符</param>
        /// <param name="computeHashLength">ComputeHash的次数</param>
        /// <returns></returns>
        public static string Md5(string input, int computeHashCount=1)
        {
            MD5 md = MD5.Create();
            byte[] buffer = Encoding.Default.GetBytes(input);
            for (int i = 0; i < computeHashCount; i++)
            {
                buffer = md.ComputeHash(buffer);
            }
            return BytesToHex(buffer);
        }

        /// <summary>
        /// MD5 加密码
        /// </summary>
        /// <param name="input">输入字符</param>
        /// <param name="computeHashLength">ComputeHash的次数</param>
        /// <returns></returns>
        public static string Md5(string input, Encoding encoding, int computeHashCount = 1)
        {
            MD5 md = MD5.Create();
            byte[] buffer = encoding.GetBytes(input);
            for (int i = 0; i < computeHashCount; i++)
            {
                buffer = md.ComputeHash(buffer);
            }
            return BytesToHex(buffer);
            //string cc= System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(viewModel.Login.UserName, "MD5").ToUpper();
            
        }

    }
}
